package com.desktop.main;


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author alex
 */
public class ImgManager
{
    private static String urlServer ="http://localhost:8084/WebService/";
    
    public boolean enviarImagen(File file,String name)
    {
        try
        {
            BufferedImage image = ImageIO.read(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            baos.close();
            
            URL url = new URL(urlServer+"ImageUpload?filename="+name+".png");           
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "image/png");
            
            ByteArrayOutputStream out = (ByteArrayOutputStream)conn.getOutputStream();
            out.write(imageInByte);
            out.flush();
            out.close();
            
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String temp, response = "";
            while ((temp = in.readLine()) != null)
            {
                response += temp + "\n";
            }
            
            in.close();
            if(response.contains("Success"))
            {
                return true;
            }
            else {
                return false;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();;
            return false;
        }
    }
    
    public Image obtenerImagen(String name)
    {
        Image image = null;
        String path = urlServer+"ImageRequest?filename="+name;
        try {
            URL url = new URL(path);;
            try {
                image = ImageIO.read(url);
            } catch (IOException ex) {
                Logger.getLogger(ImgManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(ImgManager.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            return image;
        }
    }

}
